window.onload=function(){
	//响应式布局
	document.documentElement.style.fontSize=document.documentElement.clientWidth/14.4+"px";
	$("body").css({"height":$(document).height()})
	$("#right").css("width",$(document).width()-$("#left").width())
	window.addEventListener("resize",function(){
		document.documentElement.style.fontSize=document.documentElement.clientWidth/14.4+"px"
			$("body").css({"height":$(document).height()})
		$("#right").css("width",$(document).width()-$("#left").width())
	})
//	$("body").css({"height":$(document).height()})
//	$("#right").css("width",$(document).width()-$("#left").width())
//	$("#right_children").css("height",$("#right").height()-parseFloat($("#right_children").css("margin"))*2)
}
//left操作
$li = '<li><div class="catalog_nub"><span class="name">未命名管理</span><span><div class="icon icon-add"><i style="display:none;" class="glyphicon glyphicon-plus"></i></div><div class="icon icon-change"><i class="glyphicon glyphicon-pencil"></i></div><div class="icon icon-delete"><i class="glyphicon glyphicon-remove"></i></div></span></div><input class="inp_name" size="10" hidden type="text" value="" /></li>'
$("#catalog").on("click","li",function(){
	$(this).css({"background":"#efefef"}).siblings().css({"background":"#F8F8F8"})
}).on("click",".icon-add",function(event){
	$(this).parent().parent().parent().after($li)
	event.stopPropagation()
}).on("click",".icon-change",function(event){
	var NameVal=$(this).parent().siblings(".name").html()
	$(this).parent().parent().siblings(".inp_name").val(NameVal)
	$(this).parent().parent().hide().siblings("input").show().select()
	event.stopPropagation()
})//.on("click",".icon-delete",function(event){
//	$(this).parent().parent().parent().remove()
//	event.stopPropagation()
//})
    .on("blur",".inp_name",function(event){
	if($(this).val()!=""){
	    $(this).siblings().find(".name").html($(this).val())
	    //this a hahahahahahaahahahahahahaahah
	    $.MGJ.BasicOriginModule.ModifyTablesName(this);
	}
	$(this).hide().siblings().show()
	event.stopPropagation()
}).on("keypress",".inp_name",function(event){
	if(event.keyCode == 13){
		if($(this).val()!=""){
		    $(this).siblings().find(".name").html($(this).val())
		}
		$(this).hide().siblings().show()
	}
})
//$("#add_li").on("click",function(){
//	$("#catalog").append($li)
//})

//添加select




var $iDIV = '<div style="font-size:0.2rem"><div class="col-xs-6 col-lg-6 col-md-6"><span style="white-space:nowrap;" class="col-xs-4 col-lg-4 col-md-4">名称</span><input class="col-xs-8 col-lg-8 col-md-8 tableth" type="text" size="5"  /></div><div class="col-xs-6 col-lg-6 col-md-6"><span style="white-space:nowrap;" class="col-xs-4 col-lg-4 col-md-4">类型</span><select class="col-xs-8 col-lg-8 col-md-8"><option value ="volvo">1</option><option>2</option><option>3</option><option>4</option></select></div></div>'
var TrChildLength=$("#tr_1").children().length
function LayerAdd(){
	$("#layer_add_body").append($iDIV)
}






var mytable=new Array("序号")
function UpDateTable(){
	TrChildLength=$("#tr_1").children().length
	$("#tr_1").children().remove();
	for (var i=0;i<$(".tableth").length;i++) {
		if($(".tableth").eq(i).val()!=""){
			mytable.push($(".tableth").eq(i).val())
		}
	}
	for(var i=0;i<mytable.length;i++){
		$("#tr_1").append('<th class="text-center" width="50px" style="text-overflow:ellipsis; white-space:nowrap; overflow:hidden;">'+mytable[i]+'</th>')
		if(i>=TrChildLength){
			$("#tr_1").siblings().append('<td></td>')
		}
	}
}
function initialize(){
	$("#layer_add_body").children().remove()
	$("#layer_add_body").append($iDIV)
}

//var TrChildLength_=TrChildLength;
//function AddTr(){
//	var TrLength=$("#the_table").children("tbody").children("tr").length;
//	var addtd
//	for(var i=0;i<mytable.length;i++){
//		if(i>=TrChildLength_){
//			addtd+='<td></td>'
//		}
//	}
//	$("#the_table").children("tbody").append('<tr><td>'+TrLength+'</td>'+addtd+'</tr>')
//	$("#table_right").children("tbody").append('<tr><td><button class="btn btn-sm btn-primary margin_right revise">修改</button><button class="btn btn-danger btn-sm del">删除</button></td></tr>')
//}
//修改buttom
//$("#table_right").on("click",".revise",function(){
//	$("#the_table").find("tr").eq($(".revise").index($(this))+1).children().attr("contentEditable","true")
//	//$("#the_table").find("tr").eq($(".revise").index($(this))+1).children().eq(0).attr("contentEditable","false")
//})
//删除buttom
//$("#table_right").on("click",".del",function(){
//	$("#the_table").find("tr").eq($(".del").index($(this))+1).remove()
//	$("#table_right").find("tr").eq($(".del").index($(this))+1).remove()
//	for(var i=0;i<$("#the_table").find("tr").length;i++){
//		$("#the_table").find("tr").eq(i+1).children().eq(0).html(i+1)
//	}
//})




$.MGJ.BasicOriginModule = [];

//操作
(function () {
    var _this = $.MGJ.BasicOriginModule;
    $.extend($.MGJ.BasicOriginModule, {
        //操作方法
        Dialog_AddNewOrigin:null,
        AddNewOrigin: function () {
            this.Dialog_AddNewOrigin = $.L.dialog({
                html: '<div class="row"><div class="col-xs-2 col-sm-2 col-md-2 col-lg-2 text-right"><span class="red-600">*</span>&nbsp;溯源名称:</div><div class="col-xs-10 col-sm-10 col-md-10 col-lg-10"><input class="form-control" type="text" id="originModuleName" name="ProductName" value="" /></div></div>',
                title: "新建溯源",
                width: 700,
                height: 'auto',
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: '保存',
                        click: function () {
                            _this.AddOriginsBasicModule($("#originModuleName").val());
                        }
                    },
                    "button_cancel": {
                        type: 'default',
                        text: '取消',
                        click: 'MODALMISS'
                    }
                }
            });
        },
        Dialog_AddColumnObj:null,
        Dialog_AddColumn: function () {
            if (!_this.TablesStructure) {
                $.L.msgWarning("请先从左侧选择一个模板");
                return;
            }
            this.Dialog_AddColumnObj = $.L.dialog({
                html: '<div id="layer_body" class="text-center"><div id="layer_add_body"></div><button class="btn btn-sm btn-primary" id="layer_btn" onclick="$.MGJ.BasicOriginModule.LayerAdd()"><i class="fa fa-plus fa-fw m-r-xs"></i>添加</button></div>',
                title: '',
                width: 700,
                height: 'auto',
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: '保存',
                        click: function () {
                            // _this.AddOriginsBasicModule($("#originModuleName").val());
                            var _feilds = [];
                            $("#tr_1").children().remove();
                            for (var i = 0; i < $(".tableth").length; i++) {
                                if ($(".tableth").eq(i).val() != "") {
                                    _feilds.push({ Field: $(".tableth").eq(i).val(), Type: $(".nixinhuanjiuhao").eq(i).val() });
                                }
                            }
                            $.L.ajaxHandle({
                                url: ACTION_URL('AddBasicOriginModuleTableColumn', 'TraceSource') + "?tableName=" + _this.CurrentTableInfo.TablesName,
                                data: JSON.stringify(_feilds),
                                loading: 0,
                                success: function (response) {
                                    _this.TableColBindingEvent(response);
                                    _this.GetTableRowsData(_this.TableRowsBinding);
                                }
                            })
                            _this.Dialog_AddColumnObj.close();
                        }
                    },
                    "button_cancel": {
                        type: 'default',
                        text: '取消',
                        click: 'MODALMISS'
                    }
                }
            })
            _this.LayerAdd(_this.TablesStructure);
        },

    });
})(jQuery);









(function () {
    var _this = $.MGJ.BasicOriginModule;
    $.extend($.MGJ.BasicOriginModule, {
        //表列结构
        TablesStructure: undefined,
        //表列名绑定
        TableColBindingEvent: function (colArray) {
            $("#selTableCol").children().remove();
            $("#selTableCol").append("<option value=''>选择一个搜索项</option>");
            _this.TablesStructure = colArray;
            if (_this.TablesStructure != undefined && _this.TablesStructure.length > 0) {
                $("#tr_1").children().remove();
                $.each(_this.TablesStructure, function (a, b) {
                    if (b.Field != "ID") {
                        $("#table_right").show();
                        $("#selTableCol").append("<option value=" + b.Field + ">" + b.Field + "</option>");
                        $("#tr_1").append('<th class="text-center" width="50px" style="text-overflow:ellipsis; white-space:nowrap; overflow:hidden;">' + b.Field + '</th>')
                    }
                })
            } else {
                //清除右侧数据
                //system say:"is null"
            }
        },
        AddOriginsBasicModule: function (_val) {
            if (_val != undefined && _val != "") {
                $.L.ajaxHandle({
                    url: ACTION_URL('AddBasicOriginModuleTable', 'TraceSource'),
                    data: { tablename: _val },
                    loading: 0,
                    success: function (response) {
                        _this.GetUserAllOriginModule();
                        //var _li = '<li><div class="catalog_nub"><span class="name"  onclick=" $.MGJ.BasicOriginModule.ChineseTableNameClick(this)">' + _val + '</span><span><div class="icon icon-add"><i style="display:none;" class="glyphicon glyphicon-plus"></i></div><div class="icon icon-change"><i class="glyphicon glyphicon-pencil"></i></div><div class="icon icon-delete"><i class="glyphicon glyphicon-remove"></i></div></span></div><input class="inp_name" size="10" hidden type="text" value="" /></li>'
                        //$("#catalog").append(_li);
                        _this.Dialog_AddNewOrigin.close();
                    }
                })
            } else {
                $.L.msgWarning("请输入名称");
            }
        },
        //数据库字段常用类型
        ConstMySqlFeildType:null,
        //常用库类型
        GetMySQLDBFeildType: function () {
            var _options;
            $.L.ajaxHandle({
                url: ACTION_URL('GetDBTypeList', 'TraceSource'),
                data: undefined,
                loading: 0,
                success: function (response) {
                    if (response.length > 0) {
                        $.each(response, function (a, b) {
                            _options += "<option value='" + b + "'>" + b + "</value>";
                        });
                        window.$DIV_DIV = '<div style="font-size:0.2rem"><div class="col-xs-6 col-lg-6 col-md-6"><span style="white-space:nowrap;" class="col-xs-4 col-lg-4 col-md-4">名称</span><input class="col-xs-8 col-lg-8 col-md-8 tableth" type="text" size="5"  /></div><div class="col-xs-6 col-lg-6 col-md-6"><span style="white-space:nowrap;" class="col-xs-4 col-lg-4 col-md-4">类型</span><select class="col-xs-8 col-lg-8 col-md-8 nixinhuanjiuhao">' + _options + '</select></div></div>';
                    }
                }
            })
        },
        UserAllOriginModule:[],
        //获取用户所有已建表
        GetUserAllOriginModule: function () {
            $.L.ajaxHandle({
                url: ACTION_URL('GetUserAllBasicOriginModuleTable', 'TraceSource'),
                data: undefined,
                loading:0,
                success: function (response) {
                    $("#catalog").children().remove();
                    _this.UserAllOriginModule = response;
                    if (_this.UserAllOriginModule.length > 0) {
                        $.each(_this.UserAllOriginModule, function (a, b) {
                            var _li = '<li   value=' + a + '><div class="catalog_nub" ><span class="name" title="' + b.TableChineseName + '" onclick=" $.MGJ.BasicOriginModule.ChineseTableNameClick(this)">' + b.TableChineseName + '</span><span><div class="icon icon-add"><i style="display:none;" class="glyphicon glyphicon-plus"></i></div><div class="icon icon-change"><i class="glyphicon glyphicon-pencil"></i></div><div class="icon icon-delete" arrayIndex=' + a + ' onclick="$.MGJ.BasicOriginModule.DeleteOriginModule(this)"><i class="glyphicon glyphicon-remove"></i></div></span></div><input class="inp_name" size="10" hidden type="text" value="" /></li>'
                            $("#catalog").append(_li);
                        });
                    }
                }
            })
        },
        //表中文名点击
        CurrentTableInfo:null,
        ChineseTableNameClick: function (thisObj) {
            $("#titleMess").hide();
            $("#table_right").hide();
            var rs = $(thisObj).parent().parent().val();
            $("#the_table").find("tr").not($("#tr_1")).remove();
            $("#table_right").find("tr").not($("#op_1")).remove();
            _this.CurrentTableInfo = _this.GetOriginModuleInfo($(thisObj).parent().parent().val());
            _this.InitTableStructureAndData();
        },
        InitTableStructureAndData: function () {
            if (_this.CurrentTableInfo != undefined) {
                $.L.ajaxHandle({
                    url: ACTION_URL('GetTablesStructure', 'TraceSource'),
                    loading: 0,
                    data: { tablename: _this.CurrentTableInfo.TablesName },
                    success: function (response) {
                        //列绑定
                        _this.TableColBindingEvent(response);
                        _this.GetTableRowsData(_this.TableRowsBinding);
                    }
                })
            }
        },
        //获取数组中用户模型
        GetOriginModuleInfo: function (_index) {
            if (_this.UserAllOriginModule.length == 0 || _index == undefined) {
                $.L.msgWarning("请重新刷新页面");
                return;
            }
            return _this.UserAllOriginModule[_index];
        },
        //删除点击
        DeleteOriginModule: function (thisObj) {
            var _info = _this.GetOriginModuleInfo($(thisObj).attr("arrayIndex"));
            if (_info != undefined) {
                $.L.ajaxHandle({
                    url: ACTION_URL('DeleteOriginModule', 'TraceSource'),
                    loading: 0,
                    data: {Id:_info.ID,tableName:_info.TablesName},
                    success: function (response) {
                        $(thisObj).parent().parent().parent().remove()
                        if ($(".name").length > 0) {
                            $(".name").first().click()
                        } else {
                            $("#the_table").find("tr").not($("#tr_1")).remove();
                            $("#tr_1").children().remove();
                            $("#table_right").find("tr").not($("#op_1")).remove();
                            $("#table_right").hide();
                            _this.TablesStructure = null;
                            _this.CurrentTableInfo = null;
                            $("#titleMess").show();
                        }
                        $.L.msgSuccess("删除完成");
                    }
                })
            }
        },
        //修改表名
        ModifyTablesName: function (thisObj) {
            var _new_tablename = $(thisObj).val();
            var _info = _this.GetOriginModuleInfo($(thisObj).parent().val())
            if (_info != undefined && _new_tablename != undefined) {
                if (_info.TableChineseName === _new_tablename) {
                    return;
                }
                $.L.ajaxHandle({
                    url: ACTION_URL("ModifyTableName", "TraceSource"),
                    loading: 0,
                    data: { tableName: _new_tablename, oldtableName: _info.TablesName, Id: _info.ID },
                    success: function (response) {
                        _this.GetUserAllOriginModule();
                    }
                })

            } else {
                $.L.msgWarning("请刷新页面后重试");
            }
        },
        //表添加行
        LayerAdd: function (tableCol) {
            if (!tableCol) {
                var rs = $("#layer_add_body").find("input");
                if (rs.length < 20) {
                    $("#layer_add_body").append('<div class="row"><div class="col-xs-8 col-lg-8 col-md-8"><span style="white-space:nowrap;" class="col-xs-4 col-lg-4 col-md-4">名称</span><div class="col-xs-8 col-lg-8 col-md-8"><input class="form-control tableth" type="text" size="5"/></div></div><div class="col-xs-1 col-lg-1 col-md-1 text-right" onclick="$.MGJ.BasicOriginModule.DeleteTableCol(this)"><span class="glyphicon glyphicon-trash"></span></div></div>')
                } else {
                    $.L.msgWarning("最多添加20行");
                }
            } else {
                if (tableCol.length > 0) {
                    $.each(tableCol, function (a, b) {
                        if (b.Field != "ID") {
                            $("#layer_add_body").append('<div class="row"><div class="col-xs-8 col-lg-8 col-md-8"><span style="white-space:nowrap;" class="col-xs-4 col-lg-4 col-md-4">名称</span><div class="col-xs-8 col-lg-8 col-md-8"><input class="form-control tableth" type="text" size="5" value=' + b.Field + ' disabled="disabled" /></div></div><div class="col-xs-1 col-lg-1 col-md-1 text-right" feild=' + b.Field + ' tableName=' + _this.CurrentTableInfo.TablesName + ' onclick="$.MGJ.BasicOriginModule.DeleteTableCol(this)"><span class="glyphicon glyphicon-trash"></span></div></div>')
                        }
                    })
                }
            }
        },
        //删除表列
        DeleteTableCol: function (thisObj) {
           var _feild= $(thisObj).attr("feild");
           var _tablename = $(thisObj).attr("tableName");
           if (!_feild && !_tablename) {
               $(thisObj).parent().remove();
           } else {
               $.L.ajaxHandle({
                   url: ACTION_URL("DeleteTableColumn", "TraceSource"),
                   loading: 0,
                   data: { tableName: _tablename, feildName: _feild },
                   success: function (response) {
                       _this.InitTableStructureAndData();
                       $(thisObj).parent().remove();
                   }
               })
           }
        },
        //修改行数据
        ModifyTableRow: function (thisObj) {
            var _type = $(thisObj).attr("isSave");
            if (_type == "true") {
                var _feildValue = "";
                var _child = $("#the_table").find("tr").eq($(".revise").index($(thisObj)) + 1).children();
                if (_child.length > 0) {
                    for (var i = 0; i < _child.length; i++) {
                        _feildValue += _child[i].innerText + ",";
                    }
                }
                var _id = $(thisObj).attr("id");
                $.L.ajaxHandle({
                    url: ACTION_URL('AddTableRowsData', 'TraceSource'),
                    loading: 0,
                    data: {rowData:_feildValue,Id:_id,tableName:_this.CurrentTableInfo.TablesName},
                    success: function (response) {
                        _this.GetTableRowsData(_this.TableRowsBinding);
                        //$("#the_table").find("tr").eq($(".revise").index($(thisObj)) + 1).children().removeAttr("contentEditable");
                        //$(thisObj).text("修改");
                        //$(thisObj).removeAttr("isSave");
                    }
                })
            } else {
                $("#the_table").find("tr").eq($(".revise").index($(thisObj)) + 1).children().attr("contentEditable", "true");
                $(thisObj).text("保存");
                $(thisObj).attr("isSave", "true");
            }
        },
        //添加行
        AddTableRows: function () {
            if (!_this.TablesStructure) {
                $.L.msgWarning("请先从左侧选择一个模板");
                return;
            }
            var addtd
            for (var i = 0; i < _this.TablesStructure.length - 1; i++) {
                addtd += '<td></td>'
            }
            $("#the_table").children("tbody").append('<tr>' + addtd + '</tr>')
            $("#table_right").children("tbody").append('<tr><td><button class="btn btn-sm btn-primary margin_right revise" onclick="$.MGJ.BasicOriginModule.ModifyTableRow(this)">修改</button><button class="btn btn-danger btn-sm del" onclick="$.MGJ.BasicOriginModule.DeleteTableRows(this)">删除</button></td></tr>')
        },
        //表数据获取
        GetTableRowsData: function (callback) {
            var _select = $('#selTableCol option:selected').val();
            var _search = $("#searchKey").val();
            var _where = undefined;
            if (_search && _select) {
                _where = _select + " LIKE '%" + _search + "%'";
            }
            $.L.ajaxHandle({
                url: ACTION_URL('GetTableRowsData', 'TraceSource'),
                data: { tableName: _this.CurrentTableInfo.TablesName,where:_where },
                success: function (response) {
                    if (callback) { callback(response); }
                }
            })
        },
        //表数据绑定
        TableRowsBinding: function (datarows) {
            $("#the_table").find("tr").not($("#tr_1")).remove();
            $("#table_right").find("tr").not($("#op_1")).remove();
            var _dataRow = JSON.parse(datarows);
            if (_dataRow.length > 0) {
                $.each(_dataRow, function (a, b) {
                    var addtd=undefined;
                    for (var item in b) {
                        if (item == "ID") {
                            continue;
                        }
                        addtd += "<td>"+b[item]+"</td>";
                    }
                    $("#the_table").children("tbody").append('<tr>' + addtd + '</tr>')
                    $("#table_right").children("tbody").append('<tr><td><button class="btn btn-sm btn-primary margin_right revise" id=' + b["ID"] + ' onclick="$.MGJ.BasicOriginModule.ModifyTableRow(this)">修改</button><button class="btn btn-danger btn-sm del" id=' + b["ID"] + ' onclick="$.MGJ.BasicOriginModule.DeleteTableRows(this)">删除</button></td></tr>')
                })
            }
        },
        //删除表行数据
        DeleteTableRows: function (thisObj) {
            var _id = $(thisObj).attr("Id");
            if (!_id) {
                $.L.msgWarning("刷新页面后重试");
                return;
            }
            $.L.ajaxHandle({
                url: ACTION_URL('DeleteTableRowsData', 'TraceSource'),
                data: { Id: _id, tableName: _this.CurrentTableInfo.TablesName },
                loading: 0,
                success: function (response) {
                    $("#the_table").find("tr").eq($(".del").index($(thisObj)) + 1).remove()
                    $("#table_right").find("tr").eq($(".del").index($(thisObj)) + 1).remove()
                    for (var i = 0; i < $("#the_table").find("tr").length; i++) {
                        $("#the_table").find("tr").eq(i + 1).children().eq(0).html(i + 1)
                    }
                }
            })
        }
    });
})(jQuery);

//other
(function () {
    var _this = $.MGJ.BasicOriginModule;
    $.extend(_this, {
        Init: function () {
            _this.GetUserAllOriginModule();
            _this.GetMySQLDBFeildType();
        }
    })
})(jQuery)